﻿using Mysoft.ModelAnalysis.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mysoft.Utility;
using 检查页面开放.Business;
using 检查页面开放.Models;
using System.Globalization;
using MdDocGenerator.Util;
using MdDocGenerator;
using System.Net.Mime;
using System.Text;
using System.Threading;

namespace 检查页面开放.Controllers
{
    /// <summary>
    /// 获取App对外开放的接口
    /// </summary>
    public class GetAppApiController : Controller
    {
        GetAppApi getAppApi = new GetAppApi();
        MethodLogBusiness methodLogBusiness = new MethodLogBusiness();
        YunCeBusiness yunCeBusiness = new YunCeBusiness();
        YunCeForSjzx yunCeForSjzx = new YunCeForSjzx();

        /// <summary>
        /// interface、appservice方法展示页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            getAppApi.GetApi();
            getAppApi.GetInterFaceApi();
            return View(getAppApi.List);
        }

        //public ActionResult InterfaceMethod()
        //{
        //    getAppApi.GetInterFaceApi();
        //    return View(getAppApi.List);
        //}

        #region 接口日志
        /// <summary>
        /// 接口日志页面
        /// </summary>
        /// <returns></returns>
        public ActionResult MethodLog()
        {
            //getAppApi.GetApi();
            ViewBag.MethodLogList = methodLogBusiness.Query();
            return View();
        }

        /// <summary>
        /// 记录
        /// </summary>
        /// <param name="logName"></param>
        public void JiLu(string logName)
        {
            if (string.IsNullOrEmpty(logName))
            {
                throw new BusinessLogicException("名称不能为空！");
            }
            if (methodLogBusiness.IsExiste(logName))
            {
                throw new BusinessLogicException("名称重复！");
            }

            List<AppDataSource> appDataSource = DataSourceHelp.GetModelDlls(System.Web.HttpContext.Current.Server.MapPath(PathConst.AppDataSouce));
            methodLogBusiness.Add(new Models.MethodLog
            {
                Name = logName,
                Data = Newtonsoft.Json.JsonConvert.SerializeObject(getAppApi.GetModels(appDataSource)),
                CreateTime = DateTime.Now
            });

        }

        /// <summary>
        /// 比较
        /// </summary>
        /// <param name="oldLog"></param>
        /// <param name="newLog"></param>
        /// <returns></returns>
        public string Compare(int oldLog, int newLog)
        {
            var log1 = methodLogBusiness.Get(oldLog);
            var log2 = methodLogBusiness.Get(newLog);
            var modelList1 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model>>(log1.Data);
            var modelList2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model>>(log2.Data);

            List<ModelDiff> modelDiffs = new List<ModelDiff>();
            foreach (var model1 in modelList1)
            {
                var model2 = modelList2.FirstOrDefault(t => t.Name == model1.Name);
                //如果为空，默认一个值
                if (model2 == null)
                {
                    model2 = new Model
                    {
                        Name = "",
                        MethodList = new List<MethodInfo>()
                    };
                }
                modelDiffs.Add(new ModelDiff
                {
                    Model = model1,
                    MethodDiffs = GetAppApi.CompareDll(model1.MethodList, model2.MethodList)
                });
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(modelDiffs);
        }

        #endregion

        #region 云测接口完成情况

        /// <summary>
        /// 云测接口情况页面
        /// </summary>
        /// <returns></returns>
        public ActionResult YunCeIndex()
        {
            List<AllAppDataSource> allAppDataSources = DataSourceHelp.GetAllModelDlls(System.Web.HttpContext.Current.Server.MapPath(PathConst.AllAppDataSouce));
            ViewBag.AllAppDataSources = allAppDataSources;
            return View();
        }

        /// <summary>
        /// 获取系统接口结果
        /// </summary>
        /// <param name="modelCode"></param>
        /// <returns></returns>
        public string GetYc(string modelCode)
        {
            YcResult ycResult = GetYcRe(modelCode);

            return ycResult.ToJson();
        }

        /// <summary>
        /// 获取云测结果
        /// </summary>
        /// <param name="modelCode"></param>
        /// <returns></returns>
        private YcResult GetYcRe(string modelCode)
        {
            List<AllAppDataSource> allAppDataSources = DataSourceHelp.GetAllModelDlls(System.Web.HttpContext.Current.Server.MapPath(PathConst.AllAppDataSouce));
            var app = allAppDataSources.FirstOrDefault(t => t.Code == modelCode);
            if (app == null)
            {
                throw new Exception("请配置系统");
            }
            List<Model> models = yunCeBusiness.Search(app.Ycurl, app.AppDataSources);
            List<MethodInfo> allMethod = new List<MethodInfo>();
            foreach (var model in models)
            {
                allMethod.AddRange(model.MethodList);

            }
            List<InterFaceResult> interFaceResults = new List<InterFaceResult>();
            var zt = new InterFaceResult
            {
                Remark = "整体",
                Count = allMethod.Count,
                YcCount = allMethod.Count(t => t.YCIsCover == true),
                MethodList = allMethod
            };
            zt.Fgl = zt.YcCount * 1.00 / zt.Count * 100;
            interFaceResults.Add(zt);

            var dsf = new InterFaceResult
            {
                Remark = "外部第三方调用接口",
                Count = allMethod.Count(t => t.IsOpen == true),
                YcCount = allMethod.Count(t => t.IsOpen == true && t.YCIsCover == true),
                MethodList = allMethod.FindAll(t => t.IsOpen == true)
            };
            dsf.Fgl = dsf.YcCount * 1.00 / dsf.Count * 100;
            interFaceResults.Add(dsf);

            var kzxt = new InterFaceResult
            {
                Remark = "跨子系统及业务单元调用接口",
                Count = allMethod.Count(t => t.IsOpen.GetValueOrDefault() == false && t.IsPublic == true),
                YcCount = allMethod.Count(t => t.IsOpen.GetValueOrDefault() == false && t.IsPublic == true && t.YCIsCover == true),
                MethodList = allMethod.FindAll(t => t.IsOpen.GetValueOrDefault() == false && t.IsPublic == true)
            };
            kzxt.Fgl = kzxt.YcCount * 1.00 / kzxt.Count * 100;
            interFaceResults.Add(kzxt);

            var nbjk = new InterFaceResult
            {
                Remark = "业务单元内部接口",
                Count = allMethod.Count(t => t.IsPublic.GetValueOrDefault() == false),
                YcCount = allMethod.Count(t => t.IsPublic.GetValueOrDefault() == false && t.YCIsCover == true),
                MethodList = allMethod.FindAll(t => t.IsPublic.GetValueOrDefault() == false)
            };
            nbjk.Fgl = nbjk.YcCount * 1.00 / nbjk.Count * 100;
            interFaceResults.Add(nbjk);

            YcResult ycResult = new YcResult();
            ycResult.InterFaceResults = interFaceResults;
            ycResult.Models = models;
            return ycResult;
        }

        /// <summary>
        /// 获取系统接口结果-给云测平台用的
        /// </summary>
        /// <param name="modelCode"></param>
        /// <returns></returns> 
        public string GetYcForYcPt(string modelCode)
        {
            if (string.Equals(modelCode, "SJZX", StringComparison.OrdinalIgnoreCase))
            {
                return yunCeForSjzx.Search();
            }
            YcResult re = GetYcRe(modelCode);
            re.Models = null;
            return re.ToJson();
        }

        #endregion

        #region 接口参数说明
        public ActionResult InterfaceRemark()
        {
            getAppApi.GetApi();
            getAppApi.GetInterFaceApi();
            return View(getAppApi.List);
        }

        public void RefreshMd() {
            var files = Directory.GetFiles(PathConst.BinPath, ConfigHelper.Dll, SearchOption.AllDirectories)
               .ToList();
            new MarkdownGenerator().Generate(files, PathConst.MdFile);

        }

        public ActionResult ViewRemark(string name)
        {
            var content = FileHelper.GetTxt(name, Encoding.UTF8);
            ViewBag.MdContent = content;
            return View();
        }
        #endregion
    }

    public class YcResult
    {
        public List<InterFaceResult> InterFaceResults { get; set; }

        public List<Model> Models { get; set; }
    }

    public class InterFaceResult
    {
        public string Remark { get; set; }

        /// <summary>
        /// 接口数量
        /// </summary>
        public int Count { get; set; }

        /// <summary>
        /// 云测覆盖数量
        /// </summary>
        public int YcCount { get; set; }
        /// <summary>
        /// 覆盖率
        /// </summary>
        public double Fgl { get; set; }

        /// <summary>
        /// 所有方法
        /// </summary>
        public List<MethodInfo> MethodList { get; set; }
    }

}